package com.tomorrow.runner.share;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.sucun.android.utils.CacheUtils;
import cn.sucun.android.utils.ContextUtils;
import cn.sucun.android.utils.DateUtils;

/**
 *
 * Created by tomorrow on 16-5-1.
 */
public class ShareUtil {
    public static void shareSomething(Context context,ShareInfo shareInfo){
        Intent intent = new Intent(Intent.ACTION_SEND);
        if (!TextUtils.isEmpty(shareInfo.getContent())){
            if (shareInfo.getFile() != null){
                intent.setType("image/*");
                intent.putExtra(Intent.EXTRA_STREAM, shareInfo.getFile());
                intent.putExtra(Intent.EXTRA_TEXT,shareInfo.getContent());
            }
            else{
                intent.setType("text/*");
                intent.putExtra(Intent.EXTRA_TEXT,shareInfo.getContent());
            }
        }
        context.startActivity(intent);
    }

    /**

     * 根据view来生成bitmap图片，可用于截图功能

     */

    public static Bitmap getViewBitmap(View v) {

        v.clearFocus(); //

        v.setPressed(false); //

        // 能画缓存就返回false

        boolean willNotCache = v.willNotCacheDrawing();

        v.setWillNotCacheDrawing(false);

        int color = v.getDrawingCacheBackgroundColor();

        v.setDrawingCacheBackgroundColor(0);

        if (color != 0) {

            v.destroyDrawingCache();

        }

        v.buildDrawingCache();

        Bitmap cacheBitmap = v.getDrawingCache();

        if (cacheBitmap == null) {

            return null;

        }

        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

        // Restore the view

        v.destroyDrawingCache();

        v.setWillNotCacheDrawing(willNotCache);

        v.setDrawingCacheBackgroundColor(color);

        return bitmap;

    }

    /**

     * 保存Bitmap图片为本地文件

     */

    public static String saveFile(Bitmap bitmap) {
        FileOutputStream fileOutputStream;
        File dir = CacheUtils.getExternalStorageAppDataDirectory(ContextUtils.getPackageName());
        if (!dir.exists()){
            dir.mkdirs();
        }
        File image = new File(dir,DateUtils.formatDateString(System.currentTimeMillis())+".png");
        try {
            if (!image.exists()){
                image.createNewFile();
            }
            fileOutputStream = new FileOutputStream(image.getAbsolutePath());
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image.getAbsolutePath();
    }
}
